﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Enyim.Caching;
using Ayatta.Contract;
using Ayatta.Common;
using System.Web.Mvc;
using Web.Core.Security;
using Web.Seller.Models;
using Web.Core.Extensions;
using System.Web.WebPages;
using Ayatta.Contract.Domain;
using Ayatta.Common.Extension;
using System.Collections.Generic;
using Ayatta.Contract.Component;
using Microsoft.Security.Application;

namespace Web.Seller.Controllers
{
    public class AuctionController : BaseController
    {

        public AuctionController(Lazy<IInfrastructureService> infrastructure, Lazy<IPassportService> passport, Lazy<IAccountService> account, Lazy<IStoreService> store, Lazy<ITradeService> trade, Lazy<IPlayService> play, Lazy<IMiscService> misc, Lazy<IExtraService> extra, IMemcachedClient memcachedClient)
            : base(infrastructure, passport, account, store, trade, play, misc, extra, memcachedClient)
        {
        }

        public ActionResult Index(int page = 1, int size = 20, string keyword = null,
                                                          int itemId = 0, string user = null,
                                                          byte? level = null, int? group = null, bool? isZero = null,
                                                          bool? isAuto = null, bool? isVirtual = null,
                                                          bool? diffBuy = null, bool? freeBid = null,
                                                          bool? reservation = null, bool? dynamic = null,
                                                          AuctionStatus? status = null, DateTime? onlineDate = null,
                                                          DateTime? finishedDate = null)
        {
            var id = keyword.AsInt(0);
            var identity = User.Identity.Identity();
            var name = id > 0 ? string.Empty : keyword;

            var userId = user.AsInt(0);
            var userName = userId > 0 ? string.Empty : user;
            var model = new AuctionControllerModel.Index();


            model.Keyword = keyword;
            model.ItemId = itemId > 0 ? itemId.ToString() : string.Empty;
            model.User = user;
            model.Level = level;
            model.Group = group;
            model.IsZero = isZero;
            model.IsAuto = isAuto;
            model.IsVirtual = isVirtual;
            model.DiffBuy = diffBuy;
            model.FreeBid = freeBid;
            model.Reservation = reservation;
            model.Dynamic = dynamic;
            model.Status = status;
            model.OnlineDate = onlineDate;
            model.FinishedDate = finishedDate;
            model.Auctions = Store.Value.ProductAuctionPagedList(page, size, id, name, itemId, userId, userName, level, group, isZero, isAuto, isVirtual, diffBuy, freeBid, reservation, dynamic, status, onlineDate, finishedDate, identity.Id).ToPagedList(page, size);

            return View(model);
        }

        #region 添加拍品

        /// <summary>
        /// 添加新的拍品
        /// </summary>
        /// <param name="param">ItemId</param>
        /// <returns></returns>
        public ActionResult Create(int? param = null)
        {
            var identity = User.Identity.Identity();
            var model = new MagicKit<ProductItem>();

            if (param.HasValue)
            {
                var item = Store.Value.ProductItemPriceQuantityGet(param.Value, identity.Id);
                if (item != null)
                {
                    model.Status = true;
                    model.Data = item;
                }
            }
            return View(model);
        }

        /// <summary>
        /// 添加拍品
        /// </summary>
        /// <param name="param">商品Id</param>
        /// <param name="auction">拍品信息</param>
        /// <param name="dynamic">是否启用动态调整重置秒数</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(int param, ProductAuction auction, bool dynamic = false)
        {
            DateTime startTime, stopTime;
            var result = new MagicKit<string>();
            var identity = User.Identity.Identity();

            if (!DateTime.TryParse(auction.StartTime, out startTime))
            {
                result.Data = "startTime";
                return Json(result);
            }
            if (!DateTime.TryParse(auction.StopTime, out stopTime))
            {
                result.Data = "stopTime";
                return Json(result);
            }
            if (auction.DiffBuy && auction.DiffBuyLimit != DiffBuyLimit.Unlimited && auction.DiffBuyLimitValue == 0)
            {
                result.Data = "diffBuyLimitValue";
                return Json(result);
            }

            if (auction.FreeBid && auction.FreeBidLimit != FreeBidLimit.Unlimited && auction.FreeBidLimitValue == 0)
            {
                result.Data = "freeBidLimitValue";
                return Json(result);
            }
            if (dynamic)
            {
                if (auction.AlternatePrice == 0)
                {
                    result.Data = "alternatePrice";
                    return Json(result);
                }
                if (auction.AlternateInterval == 0)
                {
                    result.Data = "alternateInterval";
                    return Json(result);
                }
            }
            if (param > 0)
            {
                var item = Store.Value.ProductItemGet(param, identity.Id);
                if (item != null)
                {
                    if (auction.SkuId > 0)
                    {
                        var propText = string.Empty;
                        var sku = item.ProductItemSkus.FirstOrDefault(o => o.Id == auction.SkuId);
                        if (sku != null)
                        {
                            propText = sku.PropTexts.Aggregate(string.Empty, (c, n) => c + n + ";").TrimEnd(';');
                        }
                        auction.PropText = propText;
                    }

                    auction.ItemId = item.Id;

                    auction.ProductId = item.ProductId;
                    auction.CategoryId = item.CategoryId;
                    auction.CategoryRootId = item.CategoryRootId;
                    auction.CategoryMiddleId = item.CategoryMiddleId;

                    auction.PriceCost = 0;

                    auction.UserId = 0;
                    auction.UserName = string.Empty;
                    auction.Nickname = string.Empty;
                    auction.CurrentPrice = 0;
                    auction.ExpectedTime = null;
                    auction.Picture = item.Picture;

                    auction.Description = string.Empty;
                    auction.SellerId = identity.Id;
                    auction.OrderId = string.Empty;
                    auction.Extra = string.Empty;
                    auction.Status = AuctionStatus.Normal;
                    auction.FinishedOn = null;
                    auction.CreatedBy = User.Identity.Name;
                    auction.CreatedOn = DateTime.Now;


                    auction.IsVirtual = item.IsVirtual;

                    if (!auction.DiffBuy)
                    {
                        auction.DiffBuyLimit = DiffBuyLimit.Unlimited;
                        auction.DiffBuyLimitValue = 0;
                    }
                    if (!auction.FreeBid)
                    {
                        auction.FreeBidLimit = FreeBidLimit.Unlimited;
                        auction.FreeBidLimitValue = 0;
                    }
                    if (!dynamic)
                    {
                        auction.AlternatePrice = 0;
                        auction.AlternateInterval = 0;
                    }
                    var status = result.Status = Store.Value.ProductAuctionCreate(auction);
                    if (!status)
                    {
                        result.Message = "添加拍品失败！";
                    }
                }
                else
                {
                    result.Message = "请选择商品！";
                }
            }
            else
            {
                result.Message = "参数不正确！";
            }
            return Json(result);
        }

        #endregion

        #region 编辑拍品

        /// <summary>
        /// 编辑拍品
        /// </summary>
        /// <param name="param">拍品Id</param>
        /// <returns></returns>
        public ActionResult Edit(int param)
        {
            var identity = User.Identity.Identity();
            var model = new AuctionControllerModel.Edit();

            if (param > 0)
            {
                var auction = Store.Value.ProductAuctionGet(param, identity.Id);
                if (auction != null)
                {
                    model.Auction = auction;
                    var item = Store.Value.ProductItemPriceQuantityGet(auction.ItemId);
                    if (item != null && !item.ProductItemSkus.IsNullOrEmpty())
                    {
                        var dic = item.ProductItemSkus.ToDictionary(o => o.Id, o => o.SkuProps.Select(s => s.VName));
                        model.Dictionary = dic;
                    }
                }
            }
            return View(model);
        }

        /// <summary>
        /// 编辑拍品
        /// </summary>
        /// <param name="param">拍品Id</param>
        /// <param name="auction">拍品</param>
        /// <param name="dynamic"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(int param, ProductAuction auction, bool dynamic = false)
        {

            DateTime startTime, stopTime;
            var result = new MagicKit<string>();
            var identity = User.Identity.Identity();

            if (!DateTime.TryParse(auction.StartTime, out startTime))
            {
                result.Data = "startTime";
                return Json(result);
            }
            if (!DateTime.TryParse(auction.StopTime, out stopTime))
            {
                result.Data = "stopTime";
                return Json(result);
            }
            if (auction.DiffBuy && auction.DiffBuyLimit != DiffBuyLimit.Unlimited && auction.DiffBuyLimitValue == 0)
            {
                result.Data = "diffBuyLimitValue";
                return Json(result);
            }

            if (auction.FreeBid && auction.FreeBidLimit != FreeBidLimit.Unlimited && auction.FreeBidLimitValue == 0)
            {
                result.Data = "freeBidLimitValue";
                return Json(result);
            }
            if (dynamic)
            {
                if (auction.AlternatePrice == 0)
                {
                    result.Data = "alternatePrice";
                    return Json(result);
                }
                if (auction.AlternateInterval == 0)
                {
                    result.Data = "alternateInterval";
                    return Json(result);
                }
            }
            if (param > 0)
            {
                var target = Store.Value.ProductAuctionGet(param, identity.Id);

                if (target != null && TryUpdateModel(target))
                {
                    target.Id = param;
                    target.IsZero = auction.IsZero;
                    target.IsAuto = auction.IsAuto;
                    target.DiffBuy = auction.DiffBuy;
                    target.FreeBid = auction.FreeBid;
                    target.Reservation = auction.Reservation;

                    if (!target.DiffBuy)
                    {
                        target.DiffBuyLimit = DiffBuyLimit.Unlimited;
                        target.DiffBuyLimitValue = 0;
                    }
                    if (!target.FreeBid)
                    {
                        target.FreeBidLimit = FreeBidLimit.Unlimited;
                        target.FreeBidLimitValue = 0;
                    }
                    if (!dynamic)
                    {
                        target.AlternatePrice = 0;
                        target.AlternateInterval = 0;
                    }
                    var item = Store.Value.ProductItemGet(target.ItemId, identity.Id);
                    if (item != null)
                    {
                        if (auction.SkuId > 0)
                        {
                            var propText = string.Empty;
                            var sku = item.ProductItemSkus.FirstOrDefault(o => o.Id == auction.SkuId);
                            if (sku != null)
                            {
                                propText = sku.PropTexts.Aggregate(string.Empty, (c, n) => c + n + ";").TrimEnd(';');
                            }
                            target.PropText = propText;
                        }
                        var status = result.Status = Store.Value.ProductAuctionUpdate(target);
                        if (!status)
                        {
                            result.Message = "更新拍品失败！";
                        }
                    }
                    else
                    {
                        result.Message = "商品不存在！";
                    }
                }
                else
                {
                    result.Message = "请选择商品！";
                }
            }
            else
            {
                result.Message = "参数不正确！";
            }
            return Json(result);
        }
        #endregion

        #region 克隆拍品

        /// <summary>
        /// 克隆拍品
        /// </summary>
        /// <param name="param">拍品Id</param>
        /// <returns></returns>
        public ActionResult Clone(int param)
        {
            var identity = User.Identity.Identity();
            var model = new MagicKit<ProductAuction>();

            var auction = Store.Value.ProductAuctionGet(param, identity.Id);
            if (auction != null)
            {
                model.Status = true;
                model.Data = auction;
            }

            return View(model);
        }

        /// <summary>
        /// 克隆拍品
        /// </summary>
        /// <param name="param">拍品Id</param>
        /// <param name="auction">拍品I</param>
        /// <param name="dynamic">动态调整重置秒数</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Clone(int param, ProductAuction auction, bool dynamic = false)
        {
            DateTime startTime, stopTime;
            var result = new MagicKit<string>();
            var identity = User.Identity.Identity();

            if (!DateTime.TryParse(auction.StartTime, out startTime))
            {
                result.Data = "startTime";
                return Json(result);
            }
            if (!DateTime.TryParse(auction.StopTime, out stopTime))
            {
                result.Data = "stopTime";
                return Json(result);
            }
            if (auction.DiffBuy && auction.DiffBuyLimit != DiffBuyLimit.Unlimited && auction.DiffBuyLimitValue == 0)
            {
                result.Data = "diffBuyLimitValue";
                return Json(result);
            }

            if (auction.FreeBid && auction.FreeBidLimit != FreeBidLimit.Unlimited && auction.FreeBidLimitValue == 0)
            {
                result.Data = "freeBidLimitValue";
                return Json(result);
            }
            if (dynamic)
            {
                if (auction.AlternatePrice == 0)
                {
                    result.Data = "alternatePrice";
                    return Json(result);
                }
                if (auction.AlternateInterval == 0)
                {
                    result.Data = "alternateInterval";
                    return Json(result);
                }
            }
            if (param > 0)
            {
                var target = Store.Value.ProductAuctionGet(param, identity.Id);

                if (target != null && TryUpdateModel(target))
                {
                    target.Id = param;
                    target.IsZero = auction.IsZero;
                    target.IsAuto = auction.IsAuto;
                    target.DiffBuy = auction.DiffBuy;
                    target.FreeBid = auction.FreeBid;
                    target.Reservation = auction.Reservation;

                    if (!target.DiffBuy)
                    {
                        target.DiffBuyLimit = DiffBuyLimit.Unlimited;
                        target.DiffBuyLimitValue = 0;
                    }
                    if (!target.FreeBid)
                    {
                        target.FreeBidLimit = FreeBidLimit.Unlimited;
                        target.FreeBidLimitValue = 0;
                    }
                    if (!dynamic)
                    {
                        target.AlternatePrice = 0;
                        target.AlternateInterval = 0;
                    }

                    target.UserId = 0;
                    target.UserName = string.Empty;
                    target.Nickname = string.Empty;
                    target.CurrentPrice = 0;
                    target.ExpectedTime = null;

                    target.Description = string.Empty;
                    target.SellerId = identity.Id;
                    target.OrderId = string.Empty;
                    target.Extra = string.Empty;
                    target.Status = AuctionStatus.Normal;
                    target.FinishedOn = null;
                    target.CreatedBy = User.Identity.Name;
                    target.CreatedOn = DateTime.Now;

                    var status = result.Status = Store.Value.ProductAuctionCreate(target);
                    if (!status)
                    {
                        result.Message = "克隆拍品失败！";
                    }
                }
                else
                {
                    result.Message = "请选择拍品品！";
                }
            }
            else
            {
                result.Message = "参数不正确！";
            }
            return Json(result);
        }

        #endregion
    }
}
